'use strict'

const fetch = require('node-fetch');
const Koa = require('koa');
const route = require('koa-route');
const bodyParser = require('koa-bodyparser');

const GITEE_ROOT = 'https://gitee.com/api/v5';
const HOOK_PWD = 'xxxxxxx'; // 自己定义WebHook的密码，建议生成复杂密码，用于码云与此URL之间的权限校验
const TOKEN = 'xxxxxxx'; // 仓库Committer（即管理员）的token，从码云的设置里生成
// PR上评论的内容，可以自定义修改
const PR_COMMENT = `请检查PR是否满足[《代码合入流程指导和规范》](https://gitee.com/openharmony/powermgr_power_manager/wikis/issue-commit-pr-standard) , 否则将不会审查通过。
| 规范检查项 | 备注/样例 |
| ----- | ----- |
| Git Commit信息是否包含**修改分类** | \`feat/fix/docs/style/refactor/test/build\`，详细说明参考[社区提交规范](https://gitee.com/openharmony/powermgr_power_manager/wikis/issue-commit-pr-standard#Angular社区提交规范)章节 |
| Git Commit信息是否为**英文** | \`fix: use setting instead default value\` |
| Pull Request标题是否包含**修改分类** | \`feat/fix/docs/style/refactor/test/build\`，详细说明参考[社区提交规范](https://gitee.com/openharmony/powermgr_power_manager/wikis/issue-commit-pr-standard#Angular社区提交规范)章节 |
| Pull Request标题描述是否使用**中文** | \`fix: 使用setting替代代码中的默认值\` |
| Pull Request是否使用了**默认模板** | |
| Pull Request是否关联了Issue | |
| Pull Request是否包含了修改点 | |
| Pull Request是否包含了验证报告 | [Pull Request用例验证流水线](http://openharmony.zhangchunxin.com/frp/powerline/) |
| Pull Request的验证报告是否正确 | 验证范围与修改分类相关，详细说明参考[自验证规范](https://gitee.com/openharmony/powermgr_power_manager/wikis/issue-commit-pr-standard#自验证规范)章节 |
`

/**
 * 调用码云的OpenAPI，给PR进行评论
 * @param hook 从码云传过来的WebHook信息
 * @returns {Promise<boolean>} 评论是否成功
 */
async function processPrHook(hook) {
    let author = hook.author.username;
    let owner = hook.project.namespace
    let repo = hook.project.path
    let number = hook.number;
    let url = `${GITEE_ROOT}/repos/${owner}/${repo}/pulls/${number}/comments`;
    let res = await fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json;charset=UTF-8'
        },
        body: JSON.stringify({
            access_token: TOKEN,
            body: `@${author} ${PR_COMMENT}`
        }),
    });
    if (!res.ok) {
        console.error(`failed to post ${url}, code: ` + res.status);
        return false;
    }
    return true;
}

/**
 * PR自动评论功能的WebHook Http接口
 * @param ctx  Http请求的上下文
 */
let webHook = async ctx => {
    let hook = ctx.request.body;
    if (!hook) {
        ctx.response.status = 400;
        return;
    }
    if (!hook.password || hook.password !== HOOK_PWD) {
        console.error('hook pwd error');
        ctx.response.status = 401;
        return;
    }

    let ret;
    // 只处理新建(open)PR(merge_request_hooks)的Hook事件
    if (hook.action === 'open' && hook.hook_name === 'merge_request_hooks') {
        ret = await processPrHook(hook);
    } else {
        ctx.response.status = 403;
        return;
    }
    if (ret) {
        ctx.response.status = 200;
    } else {
        ctx.response.status = 500;
    }
}

let app = new Koa();
app.use(bodyParser());
/* 定义WebHook的URL和端口，地址为http://服务器ip:8991/hooks，此URL即为仓库WebHook中配置的地址 */
app.use(route.post('/hooks', webHook));
const PORT = 8991;
app.listen(PORT);
console.log(`OpenHarmony WebHook listening...\nhttp://localhost:${PORT}`)
